<?php
/**
 *
 * @Author nikm $
 *
 * @Date 2011-12-19 $
 */

if(!defined('FROM_INDEX')) exit('Invalid request');

/**
 * 
 * Write request & response info into log file
 * @param array $request
 * @param string $response
 * @param string $status
 */
function requestLog($request, $response, $status)
{
	if(!defined('LOG_REQUEST') || !LOG_REQUEST)
	{
		return true;
	}

	$date = date('Y-m-d H:i:s');

	$path = LOG_PATH.date('Y/m/d/');

	if(!file_exists($path))
	{
		mkdir($path, 0777, true);
	}

	$cookie = var_export($_COOKIE, true);
	$request = var_export($request, true);

	$logInfo = '----------------------- request start -----------------------'."\r\n";
	$logInfo .= "Date Time: ".$date."\r\n";
	$logInfo .= "IP: ".client_ip()."\r\n";
	$logInfo .= "Status: ".$status."\r\n\r\n";
	$logInfo .= "Cookie \r\n\r\n";
	$logInfo .= $cookie."\r\n\r\n";
	$logInfo .= "Request \r\n\r\n";
	$logInfo .= $request."\r\n\r\n";
	$logInfo .= "Response \r\n\r\n";
	$logInfo .= $response."\r\n\r\n";
	$logInfo .= "EOF \r\n\r\n";
	$logInfo .= '----------------------------------------------'."\r\n\r\n";

	writeLog($path.'request.log', $logInfo);
}

function writeLog($file, $msg)
{
	$handle = fopen($file, "a");
	$fileWrite = fwrite($handle, $msg."\r\n");
	fclose($handle);
}

/**
 * 
 * Show http response in json format
 * @param string $code: Message code
 * @param string $status: Response status
 */
function show_msg($code, $status)
{	
	include_once ROOT_PATH .'servlet/conf/msg.conf.php';
	
	$result['version'] = API_VERSION;
	$result['status'] = $status;
	$result['message_code'] = (is_array($message) && isset($message[$code])) ? $code : '';;
	//$result['message'] = (is_array($message_zh) && isset($message_zh[$code])) ? $message_zh[$code] : '';

	$json = json_encode($result);
	
	requestLog($_REQUEST, (string)$json, STATUS_E);
	
	echo $json;
	exit();
}


/**
 * Parse request json string to array
 * @param string $json
 * @return array
 */
function parse_json($json)
{
	$result = false;

	if($json)
	{
		$json = str_replace('\n', '', $json);
		$json = stripslashes(trim($json));
		$result = @json_decode($json, true);
	}

	return $result;
}